package com.atguigu.spzx.manager.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.convert.impl.UUIDConverter;
import com.atguigu.spzx.manager.service.ValidateCodeService;
import com.atguigu.spzx.model.vo.system.ValidateCodeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {



    @Autowired
    StringRedisTemplate redisTemplate;
    @Override
    public ValidateCodeVo generaterValidateCode() {
        //1.hutool包下的一个工具类
         CircleCaptcha circleCapcha =  CaptchaUtil.createCircleCaptcha(150,50,4,10);

         //2.从circleCaptcha对象中解析两个属性
        String code = circleCapcha.getCode(); //4位字符
        String imageBase64 = circleCapcha.getImageBase64();//前端显示base64的字符串


        //3.四位验证码保存到redis中
        String codekey = UUID.randomUUID().toString().replaceAll("-","");
        //token
        String key = "user:code:" + codekey;
        //四位验证码的值就是value
        String value = code;

        redisTemplate.opsForValue().set(key,value,5, TimeUnit.MINUTES);

        //4.封装validateCodeVo
        ValidateCodeVo validateCodeVo = new ValidateCodeVo();
        //传递给前端,将来在登录时,前端还会将codekey传递给登录接口,登录接口需要查询redis中正确的验证码
        //redis中的key = user:code:codekey value = 正确的验证码
        validateCodeVo.setCodeKey(codekey);
        validateCodeVo.setCodeValue("data:image/png;base64," + imageBase64);



        return validateCodeVo;
    }



}
